package com.salim.leetcode.$20;

import lombok.extern.slf4j.Slf4j;

/**
 * 题目 https://leetcode.com/problems/valid-parentheses/
 * 答案 https://leetcode.com/articles/valid-parentheses/
 */
@Slf4j
public class ValidParentheses {

    /**
     * ( = 40
     * ) = 41
     * [ = 91
     * ] = 93
     * { = 123
     * } = 125
     */
    char rl=40;
    char rr=41;
    char sl=91;
    char sr=93;
    char bl=123;
    char br=125;

    /**
     * 方法1 类似一种出入栈的方式
     * 还能更快
     * @param s
     * @return
     */
    public boolean isValid(String s) {
        //长度单数直接返回
        if(s.length()%2!=0){
            return false;
        }
        //StringBuilder left = new StringBuilder();
        StringBuilder right = new StringBuilder();
        for(int i=0;i<s.length();i++){

            char now = s.charAt(i);
            if(now==rl||now==sl||now==bl){
                //正的 记录
                right.insert(0,reverse(now));
            }else if(now==rr||now==sr||now==br){
                //反的 触发校验
                //使用反字符串比较
                //({}) i=2 l=2-1
                //如果反字符串index超过字符串
                if(right.length()==0){
                    return false;
                }
                if(s.length()<i+right.length()){
                    return false;
                }

                if(right.charAt(0)==now){
                    right.delete(0,1);
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }
        if(right.length()>0){
            return false;
        }
        return true;
    }

    private char reverse(char i){
        if(i==rl){
            return rr;
        }else if(i==sl){
            return sr;
        }else if(i==bl){
            return br;
        }else{
            return 0;
        }
    }

    public static void main(String[] args){
        ValidParentheses v = new ValidParentheses();
        log.info("validParentheses输出结果1：{}",v.isValid("()[]{}"));
        log.info("validParentheses输出结果2：{}",v.isValid("()"));
        log.info("validParentheses输出结果3：{}",v.isValid("(]"));
        log.info("validParentheses输出结果4：{}",v.isValid("([)]"));
        log.info("validParentheses输出结果5：{}",v.isValid("{[]}"));
        log.info("validParentheses输出结果6：{}",v.isValid("(("));
        log.info("validParentheses输出结果7：{}",v.isValid(""));
        log.info("validParentheses输出结果8：{}",v.isValid("(()"));
        log.info("validParentheses输出结果9：{}",v.isValid("){"));
        log.info("validParentheses输出结果10：{}",v.isValid("(([]){})"));
    }



}
